package com.bondex.charter.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 监听MQ信息
 */
@Configuration
public class RabbitMQConfig {

	//region 连接工厂相关

	@Value("${mq.formal.host}")
	private String host;
	@Value("${mq.formal.port}")
	private int port;
	@Value("${mq.formal.userName}")
	private String userName;
	@Value("${mq.formal.password}")
	private String password;

	@Bean
	public ConnectionFactory connectionFactory() {
		CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
		connectionFactory.setHost(host);
		connectionFactory.setPort(port);
		connectionFactory.setUsername(userName);
		connectionFactory.setPassword(password);
		return connectionFactory;
	}

	@Bean
	public RabbitAdmin rabbitAdmin() {
		return new RabbitAdmin(connectionFactory());
	}

	@Bean
	public RabbitTemplate rabbitTemplate() {
		return new RabbitTemplate(connectionFactory());
	}

	//endregion

	//region 主要监听

	//主队列
	@Value("${mq.listener.queue}")
	private String LISTENER_QUEUE;

	@Bean
	public Queue mqListenerQueue() {
		return new Queue(LISTENER_QUEUE, true, false, false);
	}

	//region 监听EDI报文变更
	@Value("${mq.listener.edi_raw.exchange}")
	private String EDI_RAW_EXCHANGE;
	@Value("${mq.listener.edi_raw.routing_key}")
	private String EDI_RAW_ROUTING_KEY;

	@Bean
	public TopicExchange ediRawExchange() {
		return new TopicExchange(EDI_RAW_EXCHANGE, true, false);
	}

	@Bean
	public Binding ediRawBinding() {
		return BindingBuilder.bind(mqListenerQueue()).to(ediRawExchange()).with(EDI_RAW_ROUTING_KEY);
	}

	//endregion

	//endregion

}
